package com.qf.emp.controller;

import com.alibaba.fastjson.JSON;
import com.qf.emp.constants.BaseConstants;
import com.qf.emp.entity.Emp;
import com.qf.emp.service.IEmpService;
import com.qf.emp.service.impl.EmpServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/EmpServlet/*") // 现在的写法,/EmpServlet/addUser
public class EmpServlet extends BaseServlet {

    private IEmpService empService = new EmpServiceImpl();

    public String list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.调用业务层获取数据
        List<Emp> empList = empService.list();
        // 2.把数据放到域对象中
        req.setAttribute("empList", empList);
        // 3.跳转到页面
        return BaseConstants.BASE_FORWARD + ":emp/empList.jsp";
    }

    // 这个方法最终返回的JSON数据
    public String addEmpAsync(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.获取前端传递的数据
        String text = req.getReader().readLine();
        // 2.把JSON转成对象
        Emp t = JSON.parseObject(text, Emp.class);
        // 3.入库
        boolean save = empService.save(t);
        // 4.响应
        return outJson(save);
    }
    public String updateEmpAsync(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.获取前端传递的数据
        String text = req.getReader().readLine();
        // 2.把JSON转成对象
        Emp t = JSON.parseObject(text, Emp.class);
        // 3.入库
        boolean save = empService.update(t);
        // 4.响应
        return outJson(save);
    }


    public String removeEmp(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.获取删除的id
        String empno = req.getParameter("empno");
        // 2.调用业务层删除
        return outRedirect(empService.remove(Integer.parseInt(empno)), "EmpServlet/list");
    }

    public String getEmpById(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1.获取需要查询的员工编号
        String empno = request.getParameter("empno");
        // 2.调用业务层查询
        Emp emp = empService.byId(Integer.parseInt(empno));
        // 3.把数据放到域对象中
        request.setAttribute("emp", emp);
        // 4.跳转到jsp
        return BaseConstants.BASE_FORWARD + ":" + "emp/updateEmp.jsp";
    }

}
